package cn.ehcache.abstracts.utils;

import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.ExpiryPolicy;

import java.time.Duration;

/**
 * 类简介:缓存实用程序
 *
 * @Author: ShangGuan
 * @Time: 2024/05/13
 **/
public class CacheUtil {


    /**
     * 新缓存管理器生成器
     *
     * @param cacheName  缓存名称
     * @param timeToLive 活下去时间
     * @param key        钥匙
     * @param value      价值
     * @return {@link CacheManager}
     */
    public static <K, V> CacheManager newCacheManagerBuilder(String cacheName, Duration timeToLive, Class<K> key, Class<V> value) {
        if (timeToLive == null) {
            return newCacheManagerBuilder(cacheName, key, value);
        }
//        Duration.ofMinutes(2))
        ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToLiveExpiration(timeToLive);
        CacheConfiguration<K, V> build = CacheConfigurationBuilder
                .newCacheConfigurationBuilder(
                        key, value,
                        ResourcePoolsBuilder.heap(10000)) // 设置缓存容量
                .withExpiry(expiry) // 设置过期策略
                .build();
        return CacheManagerBuilder.newCacheManagerBuilder()
                .withCache(cacheName, build)
                .build(true);
    }

    public static <K, V> CacheManager newCacheManagerBuilder(String cacheName, Class<K> key, Class<V> value) {

        CacheConfiguration<K, V> build = CacheConfigurationBuilder
                .newCacheConfigurationBuilder(
                        key, value,
                        ResourcePoolsBuilder.heap(10000)) // 设置缓存容量
                .build();
        return CacheManagerBuilder.newCacheManagerBuilder()
                .withCache(cacheName, build)
                .build(true);
    }


}
